package info.nightbrest.agt.client;

import com.google.gwt.http.client.*;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.inject.Inject;
import info.nightbrest.agt.shared.rpc.RpcParserException;

import java.util.HashMap;
import java.util.Map;

public class AgtDispatcherImpl implements AgtDispatcher
{
	private Map<Class, Result> resultMap = new HashMap<Class, Result>();

	@Inject
	public AgtDispatcherImpl()
	{
	}

	@Override
	public <R extends Result> Result getLastResult(Class<R> clazz)
	{
		return resultMap.get(clazz);
	}

	@Override
	public <A extends Action<R>, R extends Result> void action(final A action, final AsyncCallback<R> callback)
	{
		RequestBuilder builder = new RequestBuilder(action.getRequestMethod(), action.getRequestUri());

		try
		{
			builder.setHeader("Content-Type", Constants.RPC_DATA_FORMAT.getContentType());
			builder.sendRequest(action.getPostData(Constants.RPC_DATA_FORMAT), new RequestCallback()
			{
				public void onError(Request request, Throwable e)
				{
					callback.onFailure(e);
				}

				public void onResponseReceived(Request request, Response response)
				{
					try
					{
						action.onResponseReceived(request, response);
						R result = action.getResult();

						if (result.isOk())
						{
							resultMap.put(result.getClass(), result);
						}
						callback.onSuccess(result);

					}
					catch (RpcParserException e)
					{
						e.printStackTrace();
					}
				}
			});
		}
		catch (Exception e)
		{
			callback.onFailure(e);
		}
	}
}
